namespace ETestIT.Domain.Services
{
    using System;
    using System.Collections.Generic;
    using System.Transactions;
    using Entities;
    using Repositories;

    public class CandidateResumeServiceImpl : ICandidateResumeService
    {
        private readonly IResumeRepository resumeRepository;
        private readonly ICandidateResumeRepository candidateResumeRepository;

        public CandidateResumeServiceImpl(
            IResumeRepository resumeRepository, 
            ICandidateResumeRepository candidateResumeRepository)
        {
            this.resumeRepository = resumeRepository;
            this.candidateResumeRepository = candidateResumeRepository;
        }

        public void Add(Candidate candidate, JobTitle jobTitle, Resume resume)
        {
            var candidateResume = new CandidateResume {TheResume = resume, IdJobTitle = jobTitle.Id, TheCandidate = candidate};

            using(var tx = new TransactionScope())
            {
                resume.Version = 1;
                resumeRepository.Add(resume);
                candidateResumeRepository.Add(candidateResume);
                tx.Complete();
            }

        }

        public void Update(Guid previosResumeId, Resume resume)
        {
            var candidateResume = candidateResumeRepository.GetByResumeId(previosResumeId);
            candidateResume.TheResume = resume;

            using (var tx = new TransactionScope())
            {
                resume.Version++;
                
                resumeRepository.Add(resume);
                candidateResumeRepository.Add(candidateResume);
                tx.Complete();
            }
        }

        public void Delete(Guid resumeId)
        {
            var candidateResume = candidateResumeRepository.GetByResumeId(resumeId);

            using (var tx = new TransactionScope())
            {
                candidateResumeRepository.Delete(candidateResume.Id);
                resumeRepository.Delete(resumeId);
                tx.Complete();
            }
        }

        public IList<Resume> GetLatestVersionsResume(Guid candidateId)
        {
            var maxResumeVersions = new Dictionary<Guid, Resume>(); 

            var resumes = resumeRepository.GetAllByCandidateId(candidateId);

            foreach (var resume in resumes)
            {
                var candidateResume = candidateResumeRepository.GetByResumeId(resume.Id);

                if ((!maxResumeVersions.ContainsKey(candidateResume.IdJobTitle)) ||
                    maxResumeVersions[candidateResume.IdJobTitle].Version < resume.Version)
                    maxResumeVersions[candidateResume.IdJobTitle] = resume;
            }

            return new List<Resume>(maxResumeVersions.Values);
        }
    }
}